<template>
  <div>
    <div class="disclaimer view-container">
      <el-dialog v-model="dialogFormVisible" title="修改密码" width="500">
        <el-form :model="state" ref="formRef" :rules="state.rules">
          <el-form-item label="原密码" prop="oldpassword" :label-width="formLabelWidth">
            <el-input v-model="state.oldpassword" type="password" autocomplete="off" />
          </el-form-item>
          <el-form-item label="新密码" prop="newpassword" :label-width="formLabelWidth">
            <el-input v-model="state.newpassword" type="password" autocomplete="off" />
          </el-form-item>
          <el-form-item label="确定密码" prop="againpassword" :label-width="formLabelWidth">
            <el-input v-model="state.againpassword" type="password" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="confirm"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <div class="titlebar" @mousedown.self="handleMouseDown">
      <div class="left no-drag">
        <history-control />
      </div>

      <div class="right no-drag">
        <div class="headerlay">
          <div class="user">{{ systemStore.userInfo.name }}</div>
          <div class="editpassword" @click="editpassword">修改密码</div>
          <div class="outlogin" @click="outlogin">退出登录</div>
        </div>
        <div class="system-functions">
          <!-- <language class="system-function" /> -->
          <!-- <system-skin class="system-function" /> -->
        </div>
        <system-control class="mg-left" />
      </div>
    </div>

    <login-view v-model:visible="isVisible.dialogLoginView" />
  </div>
</template>

<script setup lang="ts">
import HistoryControl from './HistoryControl.vue';
// import Language from './Language.vue';
import SystemControl from './SystemControl.vue';
// import SystemSkin from './SystemSkin.vue';
import { reactive, ref, unref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { updatePassword } from '@renderer/src/utils/ipc';
import { userSystemStore } from '@/store';
import { hideWindow, showWindow } from '@/utils/webVideoCtrl';
import LoginView from '@/pages/login/LoginView.vue';

const isVisible = reactive({
  dialogLoginView: false,
});

const handleMouseDown = (event) => {
  if (event.detail === 2) {
    window.electron.ipcRenderer.send('win:invoke', 'max');
  }
};

const systemStore = userSystemStore();

const formRef = ref();

const state = reactive({
  oldpassword: '',
  newpassword: '',
  againpassword: '',
  rules: {
    oldpassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
    newpassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      {
        pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,16}$/,
        message: '密码为6-16位，请包含英文字母、数字，字母区分大小写',
        trigger: 'blur',
      },
    ],
    againpassword: [
      { required: true, message: '请确认密码', trigger: 'blur' },
      {
        // 使用validator函数来比较新密码和确认密码是否一致
        validator: (rule, value, callback) => {
          if (value !== state.newpassword) {
            callback(new Error('两次密码输入不一致'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
  },
});

const dialogFormVisible = ref(false);
const formLabelWidth = '80px';

function outlogin() {
  hideWindow();
  ElMessageBox.confirm('是否确定退出登录?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true,
  })
    .then(() => {
      ElMessage({
        type: 'success',
        message: '退出成功',
      });
      systemStore.logout();
      isVisible.dialogLoginView = true;
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消退出',
      });
      showWindow();
    });
}

function editpassword() {
  state.oldpassword = '';
  state.newpassword = '';
  state.againpassword = '';
  dialogFormVisible.value = true;
  hideWindow();
}

function cancel() {
  dialogFormVisible.value = false;
  state.oldpassword = '';
  state.newpassword = '';
  state.againpassword = '';
  showWindow();
  formRef.value.resetFields();
  showWindow();
}

const confirm = async () => {
  try {
    // 确保 formRef 是一个响应式的引用，并且调用 validate 方法等待其返回结果
    const isValid = await unref(formRef).validate();

    if (!isValid) {
      ElMessage.error('表单验证失败');
      return;
    }

    if (state.newpassword !== state.againpassword) {
      ElMessage.error('两次密码输入不一致');
      return;
    }

    if (state.oldpassword !== systemStore.getUserInfo().password) {
      ElMessage.error('原始密码输入错误');
      return;
    }

    const params = {
      id: systemStore.getUserInfo().id.toString(),
      password: state.newpassword,
    };

    await updatePassword(params);

    // 更新用户信息中的密码
    const loginInfo = systemStore.getUserInfo();
    loginInfo.password = state.newpassword;

    ElMessage.success('更新成功');
    dialogFormVisible.value = false;
    showWindow();
  } catch (err) {
    console.error('确认过程中发生错误:', err);
    ElMessage.error(`更新异常: ${err}`);
    showWindow();
  }
};
</script>

<style lang="less" scoped>
.headerlay {
  display: flex;
  align-items: center;
  justify-items: center;
  justify-content: end;
  .editpassword {
    margin-right: 10px;
    cursor: pointer;
  }
  .user {
    font-color: blur;
    margin-right: 10px;
  }
  .outlogin {
    margin-right: 10px;
    cursor: pointer;
  }
}
.titlebar {
  -webkit-app-region: drag;
  display: flex;
  justify-content: space-between;
  height: 32px;
  margin: var(--td-comp-margin-m) var(--td-comp-margin-xs) var(--td-comp-margin-m) 0;

  .no-drag {
    -webkit-app-region: no-drag;
  }

  .mg-left {
    margin-left: var(--td-comp-margin-l);
  }

  .left {
    height: 100%;
    display: flex;
  }

  .right {
    display: flex;
    flex-direction: row;
    align-items: center;

    .system-functions {
      display: flex;
      align-items: center;
      justify-content: space-around;
      background: var(--td-bg-color-container);
      border-radius: var(--td-radius-default);

      & > .system-function:first-of-type {
        margin-left: 0;
      }

      .system-function {
        margin-left: var(--td-comp-margin-xs);
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;

        :deep(.t-button__text) {
          svg {
            color: var(--td-text-color-placeholder);
          }
        }

        :deep(.t-button--variant-text) {
          &:hover {
            border-color: transparent;
            background-color: transparent;

            .t-button__text {
              svg {
                color: var(--td-primary-color);
              }
            }
          }
        }
      }
    }
  }
}
</style>
